<?php
declare(strict_types=1);

namespace LiLei\MyLanguage;

class MyLanguage
{
    // 默认语言
    // 语言文件的路径
    // 引入语言文件

    public string $path = '/language/default.php';
    public array $message = [];

    /**
     * @throws \Exception
     */
    public function __construct(string $path = '')
    {
        if (file_exists($path))
        {
            $this->setPath($path);
        } else {
            $this->loadLanguageFile();
        }
    }// __construct() end

    /**
     * 加载语言文件
     *
     * @return void
     * @throws
     */
    public function loadLanguageFile(): void
    {
        $message = [];
        if (file_exists($this->path))
        {
            $message = require $this->path;
        } elseif(dirname(__FILE__).$this->path) {
            $message = require dirname(__FILE__) . $this->path;
        } else {
            throw new \Exception("language file not found {$this->path}");
        }

        $this->message = $message;
    }// loadLanguageFile() end

    /**
     * 自定义语言内容
     *
     * @param string $key
     * @param string $language
     * @param string $message
     * @return $this|null
     */
    public function customMessage(string $key, string $language, string $message): ?MyLanguage
    {
        $this->message[$key][$language] = $message;

        return $this;
    }// customMessage() end

    /**
     * 获取语言内容
     *
     * @param string $key
     * @param string $language
     * @return string
     * @throws \Exception
     */
    public function getMessage(string $key, string $language = 'zh_cn'): string
    {
        if (is_null($this->message[$key][$language])) throw new \Exception("Unknown content [{$key}][$language]");

        return $this->message[$key][$language];
    }// getMessage() end

    /**
     * 设置路径
     *
     * @param string $path
     * @return $this
     * @throws
     */
    public function setPath(string $path): ?MyLanguage
    {
        $this->path = $path;
        $this->loadLanguageFile();

        return $this;
    }// setPath() end

    /**
     * 获取路径
     *
     * @return string
     */
    public function getPath(): string
    {
        return $this->path;
    }// getPath() end
}